<template>
  <div class="chart_container" v-if="currentList && currentList.length">
    <template v-for="code in currentList" :key="code">
      <template v-for="a in channel" :key="a">
        <template v-for="b in _dataType" :key="b">
          <div :class="['box', a, b, code.replaceAll('.', '')]"></div>
        </template>
      </template>
    </template>
  </div>
  <div class="chart_container empty" v-else>
    <Empty :image="simpleImage"></Empty>
  </div>
</template>

<script setup lang="tsx">
import { computed, inject, nextTick, onMounted, ref, watch } from 'vue';
import { Empty, message } from 'ant-design-vue';
import dayjs from 'dayjs';
import * as echarts from 'echarts';
import 'echarts/theme/macarons';

const simpleImage = Empty.PRESENTED_IMAGE_SIMPLE;
const props = defineProps({
  channel: {
    type: Array,
    default: () => [],
  },
  dataType: {
    type: Array,
    default: () => [],
  },
  deviceInfo: {
    type: Array,
    default: () => [],
  },
  instanceOptions: {
    type: Object,
    default: () => {},
  },
  fetchInfoApi: {
    type: Function,
    required: true,
    default: () => {},
  },
  formatTrigger: {
    type: null,
  },
  loading: {
    type: Boolean,
    default: true,
  },
});

const colorEnum = {
  EIZ: '#FF5C8D',
  EIE: '#FFE54E',
  EIN: '#39D0FF',
};
watch(
  () => props,
  (val) => {
    nextTick(() => {
      getInfo(val.dataType, val.channel, val.deviceInfo);
    });
  },
  { deep: true, immediate: true },
);
const { fetchInfoApi, formatTrigger, instanceOptions } = props;
const dataInfo = ref({});

const _dataType = computed(() => {
  const list = instanceOptions.dataTypeList.map((i) => i.value);
  return props.dataType.filter((i) => list.includes(i));
});

const currentList = computed(() => {
  const asyncKeys = Object.keys(dataInfo.value);
  const list = instanceOptions.deviceInfoList
    .filter((i) => i.disabled)
    .map((i) => i.label);
  const newList = devices.value
    .filter((i) => asyncKeys.includes(i))
    .filter((i) => !list.includes(i));
  console.log(newList, 'newList');

  return newList;
});

const getDataInfo = async () => {
  const result = await fetchInfoApi!();
  dataInfo.value = result;
};
getDataInfo();

const processFn = (code, node, data, type, channel) => {
  if (!data) return;
  if (formatTrigger && typeof formatTrigger === 'function')
    return formatTrigger(code, node, data, type, channel);
  const seriesData = data.map((item) => {
    return {
      value: item[conversionType(type)]?.toFixed(6),
      s: item.s,
      d: item.d,
      // dl: this.waveData?.[key]?.[keys]?.delay,
      i: item.i,
      ch: item.ch,
      name: conversionType2(type),
    };
  });
  const xData = data.map((item) => dayjs(item[0]).format('HH:mm:ss'));
  const max = Math.max.call(null, ...seriesData.map((a) => a.value));
  const min = Math.min.call(null, ...seriesData.map((a) => a.value));
  //  ' ' + seriesData[0].i +  '.' + seriesData[0].ch +
  const text =
    '▍ ' +
    code +
    '-' +
    seriesData[0].name +
    '-' +
    conversion2(channel) +
    '   Amax=' +
    max +
    '  Amin=' +
    min;

  const color = colorEnum[channel];

  return { text, node, seriesData, xData, color };
};
const devices = ref([]);
const getInfo = (typeList, channelList, deviceList) => {
  devices.value = deviceList;
  for (const code in dataInfo.value) {
    if (!deviceList.includes(code)) throw new Error('没有设备');
    typeList.forEach((type) => {
      channelList.forEach((channel) => {
        nextTick(() => {
          const node = document.querySelector(
            `.${type}.${channel}.${code.replaceAll('.', '')}`,
          );
          if (!node) return;

          const result = processFn(
            code,
            node,
            dataInfo.value[code][conversion(channel)],
            type,
            channel,
          );

          init(result);
        });
      });
    });
  }
};

const init = ({ text, node, seriesData, xData, color }) => {
  const chart = echarts.init(node);
  const option = {
    title: {
      text,
      textStyle: {
        color: '#fff',
        fontSize: 14,
      },
      top: '4%',
      left: '4%',
    },
    grid: [
      {
        top: '25%',
        bottom: '15%',
        right: '3%',
        left: '4%',
        show: true,
      },
    ],
    xAxis: [
      {
        show: true,
        type: 'category',
        splitLine: {
          show: false,
          lineStyle: {
            type: 'dashed',
          },
        },
        // splitNumber: 8,
        axisLine: {
          show: false,
          onZero: false,
        },
        // inverse: true,
        axisTick: {
          show: false,
        },
        data: xData,
        axisLabel: {
          show: true,
          color: '#fff',
          fontSize: '12px',
          showMaxLabel: true,
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        splitLine: {
          show: false,
          lineStyle: {
            type: 'dashed',
          },
        },
        axisLine: {
          show: false,
          onZero: false,
        },
        max: function (value) {
          //取最大值向上取整为最大刻度
          return value.max;
        },
        min: function (value) {
          //取最大值向上取整为最大刻度
          return value.min;
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          show: true,
          color: '#fff',
          // color: '#fff',
          fontSize: '12px',
        },
      },
    ],
    dataZoom: [
      {
        show: false,
        type: 'inside',
        filterMode: 'none',
        start: 0,
        end: 100,
      },
    ],
    series: [
      {
        data: seriesData,
        // name: this.format(key),
        type: 'line',
        symbol: 'none',
        showSymbol: false,
        markPoint: {
          symbol: 'pin',
          symbolSize: 30,
          itemStyle: {
            color: 'rgb(255, 70, 131)',
          },
          data: [
            {
              name: '最大值',
              type: 'max',
              label: { color: '#fff' },
            },
            {
              name: '最大值',
              type: 'min',
              label: { color: '#fff' },
            },
          ],
        },
        lineStyle: {
          //设置线条默认样式
          normal: {
            width: 1,
            color,
          },
          //设置线条hover样式
          emphasis: { width: 1 },
        },
      },
    ],
    animationDurationUpdate: 500,
  };
  chart.setOption(option);
  addEventListener('resize', function () {
    chart.resize();
  });
};

const conversion = (num) => {
  switch (num) {
    case 'EIZ':
      return 'Z';
    case 'EIN':
      return 'N';
    case 'EIE':
      return 'E';
  }
};
const conversion2 = (num) => {
  switch (num) {
    case 'EIZ':
      return 'EIZ-竖桥向';
    case 'EIN':
      return 'EIN-横桥向';
    case 'EIE':
      return 'EIE-纵桥向';
  }
};

const conversionType = (num) => {
  switch (num) {
    case 'accelerationData':
      return '1';
    case 'speedData':
      return '3';
    case 'displacementData':
      return '4';
  }
};

const conversionType2 = (num) => {
  switch (num) {
    case 'accelerationData':
      return '加速度(cm/s/s)';
    case 'speedData':
      return '仿真速度(cm/s)';
    case 'displacementData':
      return '仿真位移(cm)';
  }
};
</script>

<style lang="scss" scoped>
.chart_container {
  width: 100%;
  // height: 100%;
  display: grid;
  grid-template-rows: repeat(3, 1fr);
  gap: 1vh;
  .box {
    height: 25vh;
  }
  &.empty {
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.loading {
  height: 80vh;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
